<?php

class ServiceController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'doneRequest'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'addToolToService', 'addResource', 'deleteResource', 'deleteTool'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $tools = ServiceTools::model()->findAllByAttributes(array('service_id' => $id));
        $availTools = Inventory::model()->findAllByAttributes(array('obsolute' => FALSE));
        $resources = ServiceResource::model()->findAllByAttributes(array('service_id' => $id));
        $users = User::getUsersByRole("employee");
        $this->render('view', array(
            'model' => $this->loadModel($id), 'tools' => $tools, 'availTools' => $availTools, 'users' => $users, 'resources' => $resources
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Service;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Service'])) {
            $model->attributes = $_POST['Service'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Service'])) {
            $model->attributes = $_POST['Service'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Service');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Service('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Service']))
            $model->attributes = $_GET['Service'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionDeleteResource() {
        if (isset($_REQUEST['id'])) {
            try {
                $resource = ServiceResource::model()->findByPk($_REQUEST['id']);
                if (isset($resource)) {
                    $serviceid = $resource->service_id;
                    $resource->delete();
                    $this->redirect(array('service/view', 'id' => $serviceid));
                }
            } catch (Exception $ex) {
                $this->render('/common/error', array('msg' => 'Unable to Remove ' . $ex->getMessage()));
                return;
            }
        }
         $this->redirect(array('service/admin'));
    }

    public function actionAddResource() {
        if (isset($_POST['service_id']) && isset($_POST['resource_id'])) {
            $model = ServiceResource::model()->findByAttributes(array('resource' => $_POST['resource_id'], 'service_id' => $_POST['service_id']));
            if (!isset($model)) {
                $model = new ServiceResource;
                $model->service_id = $_POST['service_id'];
                $model->resource = $_POST['resource_id'];
                if ($model->save()) {
                    $this->redirect(array('service/view', 'id' => $model->service_id));
                }
            }
            $this->redirect(array('service/view', 'id' => $model->service_id));
        }
    }

    public function actionDeleteTool() {
        if (isset($_REQUEST['id'])) {
            try {
                $tool = ServiceTools::model()->findByPk($_REQUEST['id']);
                if (isset($tool)) {
                    $serviceid = $tool->service_id;
                    $tool->delete();
                    $this->redirect(array('service/view', 'id' => $serviceid));
                }
            } catch (Exception $ex) {
                $this->render('/common/error', array('msg' => 'Unable to Remove ' . $ex->getMessage()));
                return;
            }
        }
        $this->redirect(array('service/admin'));
    }

    public function actionAddToolToService() {
        if (isset($_POST['service_id']) && isset($_POST['no_item']) && isset($_POST['item_id'])) {
            $model = ServiceTools::model()->findByAttributes(array('item_id' => $_POST['item_id'], 'service_id' => $_POST['service_id']));
            if (isset($model)) {
                $model->no_item = $_POST['no_item'];
            } else {
                $model = new ServiceTools;
                $model->service_id = $_POST['service_id'];
                $model->no_item = $_POST['no_item'];
                $model->item_id = $_POST['item_id'];
            }
            if ($model->save()) {
                $this->redirect(array('service/view', 'id' => $model->service_id));
            }
        }
    }

    public function actionDoneRequest() {
        $serviceRequest = null;
        if (isset($_REQUEST['requestId'])) {
            $serviceRequest = ServiceRequest::model()->findByPk($_REQUEST['requestId']);
        } else if (isset ($_REQUEST['eventId'])) {
            $serviceRequest = ServiceRequest::getServiceRequestOfEvent($_REQUEST['eventId']);
        }
        try {
            if (!isset($serviceRequest)) {
                throw new Exception('Unable to find Service Request');
            }
            if ($serviceRequest->event->resource != Yii::app()->user->Id) {
                throw new Exception('You dont have permission to do this service');
            }
            if (!$serviceRequest->status == ServiceRequest::STATUS_SHEDULED) {
                throw new Exception('Unable to finish Service Request that alredy inactice');
            }
            if (isset($_REQUEST['finish']) && $_REQUEST['finish'] == 'true') {
                try {
                    $trn = Yii::app()->db->beginTransaction();
                    $tools = $serviceRequest->service->serviceTools;
                    foreach ($tools as $key => $_tool) {
                        $this->useTools($_tool->item_id, isset($_REQUEST['item' . $_tool->item_id]) ? $_REQUEST['item' . $_tool->item_id] : $_tool->no_item, $_REQUEST['requestId']);
                    }
                    $serviceRequest->status = ServiceRequest::STATUS_DONE;
                    $serviceRequest->update();
                    $trn->commit();
                    echo 'Saved Successfully';
                } catch (Exception $exc) {
                    $trn->rollback();
                    throw $exc;
                }
            } else {
                $this->renderPartial('/dashboard/service_done', array('serviceRequest' => $serviceRequest));
                return;
            }
        } catch (Exception $exc) {
            $this->renderPartial('/common/error', array('msg' => $exc->getMessage()));
        }
    }

    private function useTools($toolId, $count, $requestId) {
        $serviceToolsUsed = new ServiceToolsUsed();
        $serviceToolsUsed->service_rid = $requestId;
        $serviceToolsUsed->item_id = $toolId;
        $serviceToolsUsed->item_count = $count;
        Inventory::makeSale($toolId, $count);
        $serviceToolsUsed->save();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Service the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Service::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Service $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'service-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
